﻿#include "TimeThread.h"

TimeThread::TimeThread(QObject *parent) : QThread(parent)
{
    m_time = QTime(1, 0, 0);
    m_start = false;
}

void TimeThread::SetCountTime(QTime time, bool start)
{
    m_time = time;
    m_start = start;
}

void TimeThread::run()
{
    QTime  oldTime, newTime;
    oldTime.setHMS(QTime::currentTime().hour(), QTime::currentTime().minute(), QTime::currentTime().second(), 0);
    while(m_start)
    {
        msleep(250);
        newTime.setHMS(QTime::currentTime().hour(), QTime::currentTime().minute(), QTime::currentTime().second(), 0);
        if ( oldTime != newTime )
        {
            oldTime = newTime;
            m_time = m_time.addSecs(-1);
        }
        emit  RemainTimeChanged(m_time, REMAIN_TIME);
        if ( m_time == QTime(0, 0, 0) )
        {
            emit  RemainTimeChanged(m_time, TO_SHUTDOWN);
            if ( !MySystemShutdown() )
            {
                emit  RemainTimeChanged(m_time, SHUTDOWN_ERROR);
            }
            break;
        }
    }
}

bool TimeThread::MySystemShutdown()
{
    HANDLE hToken;
    TOKEN_PRIVILEGES tkp;

    //获取进程标志
    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
        return false;

    //获取关机特权的LUID
    LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, 	&tkp.Privileges[0].Luid);
    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    //获取这个进程的关机特权
    AdjustTokenPrivileges(hToken, false, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
    if (GetLastError() != ERROR_SUCCESS) return false;

    // 强制关闭计算机
    if (  !ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE,
         SHTDN_REASON_MAJOR_OPERATINGSYSTEM | SHTDN_REASON_MINOR_UPGRADE |	SHTDN_REASON_FLAG_PLANNED))
         return false;
    return true;
}
